#include "LogLocalWriter.hpp"

namespace cybertron {
	int LogLocalWriter::enable_console()
	{
		_enable_console = true;
		return 0;
	}

	int LogLocalWriter::enable_file(const std::string & file_path)
	{
		if (_enable_file) {
			std::cout << "file appender has been enabled already\n";
			return -1;
		}
		_file.open(file_path, std::ofstream::out | std::ofstream::app);
		if (!_file.is_open()) {
			std::cout << "open file error: " << file_path << "\n";
			return -1;
		}
		_enable_file = true;
		return 0;
	}

	void LogLocalWriter::run_once()
	{
		if (_enable_console || _enable_file) {
			if (_enable_file) {
				time_t now = ::time(NULL);
				if (now - _last_flush_time > 1) {
					//std::cout << "flushing\n";
					_file.flush();
					_last_flush_time = now;
				}
			}
			LogItem *p = _input_queue->dequeue();
			if (!p) {
				return;
			}
			std::string val = p->to_local_file_line() + "\n";
			delete p;
			if (_enable_console) {
				std::cout << val;
			}
			if (_enable_file) {
				_file << val;
				_file.flush();
			}
		}
		else {
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
		}
	}
}